#include "textspinbox.h"
#include <QAbstractSpinBox>
#include <QDebug>
#include <QPalette>


TextSpinBox::TextSpinBox(QWidget* parent)
    : QAbstractSpinBox(parent), m_list(0), m_index(0), m_colorMap()
{
    this->setWrapping(true);
    this->stepEnabled();
    this->setMinimumSize(150, 30);


    connect(this, SIGNAL(colorChanged(QString)),
            this, SLOT(colorChangedSlot(QString)));
}

TextSpinBox::~TextSpinBox()
{
    /* Set the pointer to null, and then the stack part of it will be
     * handled regularly.*/
    m_list = 0;
}

void TextSpinBox::setText(const QString& text)
{
    if(m_list != 0)
    {
       m_index = m_list->indexOf(text);
       this->lineEdit()->setText(m_list->at(m_index));

       setColourMap();
       emit colorChanged(m_list->at(m_index));
   }
   else
       qDebug() << "The TextSpinBog QStringList is not initialized properly.";
}
/* This is the best way, and most secure way of setting up the spin box. */
void TextSpinBox::init(const QStringList &list, const QString &text)
{
    m_list = &list;
    m_index = m_list->indexOf(text);
    this->lineEdit()->setText(m_list->at(m_index));

    setColourMap();
    emit colorChanged(m_list->at(m_index));
}

void TextSpinBox::stepBy(int steps)
{
    m_index += steps;

    if( m_index >= m_list->size() )
        m_index = 0;
    else if( m_index < 0 )
        m_index = m_list->size()-1;

    this->lineEdit()->setText( m_list->at(m_index) );

    emit colorChanged(m_list->at(m_index));
    emit textChanged();

}

QAbstractSpinBox::StepEnabled TextSpinBox::stepEnabled() const
{
    return QAbstractSpinBox::StepDownEnabled|QAbstractSpinBox::StepUpEnabled;
}

void TextSpinBox::colorChangedSlot(QString text)
{    
    //qDebug() << " Colour was changed.";
    QPalette p = this->lineEdit()->palette();
    p.setColor(QPalette::Base, m_colorMap.value(text));
    this->lineEdit()->setPalette(p);
}

void TextSpinBox::setColourMap()
{
    int size = 128 / m_list->size();
    for (int i = m_list->size() -1 ; i >= 0 ; i--)
    {
        /*These colours are hard coded to try to match the present
          octave colour settings in a different part of the program.
         */
        QColor color( 30, 127 + i*size, 127 - i*size);
        m_colorMap.insert(m_list->at(i), color);
    }
}
